package com.example.service;

import cn.hutool.core.util.ObjectUtil;
import com.example.common.enums.ResultCodeEnum;
import com.example.common.enums.RoleEnum;
import com.example.entity.Account;
import com.example.entity.Business;
import com.example.entity.User;
import com.example.exception.CustomException;
import com.example.mapper.UserMapper;
import com.example.utils.RedisLimiterUtils;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @author: 康伟奇
 * @date: 2023 - 11 - 06 10:43
 **/
//用户管理Service
@Service
public class UserService {
    @Value("9090")
    private String port;

    @Value("localhost")
    private String ip;

    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisLimiterUtils redisLimiterUtils;

    //查询所有用户
    public List<User> selectAll(User user) {
        return userMapper.selectAll(user);
    }

    //根据id查询用户
    public User selectById(Integer id) {
        return userMapper.selectById(id);
    }

    //  分页查询
    public PageInfo<User> selectPage(User user, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<User> list = userMapper.selectAll(user);
        return PageInfo.of(list);
    }

    //新增
    public void add(User user) {
        User dbUsername = userMapper.selectByUsername(user.getUsername());
        if (ObjectUtil.isNotEmpty(dbUsername)){
            throw new CustomException(ResultCodeEnum.USER_EXIST_ERROR);
        }
        if (ObjectUtil.isEmpty(user.getName())){
            user.setName(user.getUsername());
        }
        String http = "http://" + ip + ":" + port + "/files/";
        user.setAvatar(http + "1697438073596-avatar.png");
        user.setRole(RoleEnum.USER.name());
        userMapper.add(user);
    }

    //根据id删除用户
    public void delete(Integer id) {
        userMapper.deleteById(id);
    }

    //批量删除用户
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            userMapper.deleteById(id);
        }
    }

    //修改用户
    public void updateById(User user) {
        User dbUser = userMapper.selectByUsername(user.getUsername());
        if (ObjectUtil.isNotEmpty(dbUser) && !Objects.equals(dbUser.getId(), user.getId())) {
            throw new CustomException(ResultCodeEnum.USER_EXIST_ERROR);
        }
        userMapper.updateById(user);
    }

    /**
     * 登录
     */
    public Account login(Account account) {
        Account dbUser = userMapper.selectByUsername(account.getUsername());
        if (ObjectUtil.isNull(dbUser)) {
            throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
        }
        if (!account.getPassword().equals(dbUser.getPassword())) {
            throw new CustomException(ResultCodeEnum.USER_ACCOUNT_ERROR);
        }
        //进行用户登录限流，每秒只能有两个用户能够登录
        redisLimiterUtils.doRateLimit("userLoginLimit_"+ dbUser.getId());
        // 生成token
        String tokenData = dbUser.getId() + "-" + RoleEnum.USER.name();
        String token = TokenUtils.createToken(tokenData, dbUser.getPassword());
        dbUser.setToken(token);
        return dbUser;
    }

    /**
     * 普通用户注册
     * @param account
     */
    public void register(Account account) {
        String confirmPassword = account.getConfirmPassword();
        String password = account.getPassword();
        if (confirmPassword.equals(password)){
            User user = new User();
            BeanUtils.copyProperties(account, user);
            user.setName("系统用户");
            add(user);
        }else {
            throw new CustomException(ResultCodeEnum.DIFFERENT_PASSWORD);
        }
    }
}
